package ro.isdc.training.ejb3.student.service.ejb;

import javax.xml.ws.WebServiceRef;

import ro.isdc.training.ejb3.course.domain.Course;
import ro.isdc.training.ejb3.course.service.CourseService;
import ro.isdc.training.ejb3.course.service.domain.ReadCourseRequest;
import ro.isdc.training.ejb3.course.service.web.CourseServiceClient;
import ro.isdc.training.ejb3.student.dao.StudentDAO;
import ro.isdc.training.ejb3.student.domain.Enrollment;
import ro.isdc.training.ejb3.student.domain.EnrollmentId;
import ro.isdc.training.ejb3.student.domain.Student;
import ro.isdc.training.ejb3.student.service.StudentService;
import ro.isdc.training.ejb3.student.service.domain.EnrollToCourseRequest;
import ro.isdc.training.ejb3.student.service.domain.EnrollToCourseResponse;

/**
 * Student Service stateless session bean.
 * 
 * For educational purposes, the EJB configurations were
 * made in the ejb-jar.xml deployment descriptor instead of the
 * metadata annotations. For simplicity, however, the reference to
 * the web service has been annotated.
 * 
 * @author Andrei Chirila
 */
public class StudentServiceBean implements StudentService {
  
  /**
   * Student DAO reference.
   */
  private StudentDAO studentDAO;
  
  /**
   * Reference to the course web service
   */
  @WebServiceRef(value=CourseServiceClient.class, 
      wsdlLocation="http://127.0.0.1:8080/advancedejb3-ear-advancedejb3-ejb-0.0.1/CourseServiceBean?wsdl")
  private CourseService courseService;
  
  /**
   * {@inheritDoc}
   */
  public EnrollToCourseResponse enrollToCourse(
      final EnrollToCourseRequest serviceRequest) {
    Student student = studentDAO.findStudentByIdentification(serviceRequest.getStudentId());
    
    ReadCourseRequest readCourseRequest = new ReadCourseRequest();
    readCourseRequest.setCourseId(serviceRequest.getCourseId());
    Course course = courseService.readCourse(readCourseRequest).getCourse();
    
    Enrollment enrollment = new Enrollment();
    EnrollmentId enrollmentId = new EnrollmentId();
    enrollmentId.setStudentId(student.getEntityId());
    enrollmentId.setCourseId(course.getEntityId());
    enrollment.setEnrollmentId(enrollmentId);
    
    // Since student is a managed entity, any change to it will be made
    // at transaction commit
    student.addEnrollment(enrollment);
    
    EnrollToCourseResponse serviceResponse = new EnrollToCourseResponse();
    serviceResponse.setEnrolled(true);
    
    return serviceResponse;
  }

}
